package com.iot08.common.utils; /**
 * @author weichao 1299101858@qq.com
 * @version 1.0
 * @date 12/17/22 1:59 PM
 */

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import java.util.Base64;


public class AES256ECB {

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding";

    static {
        //Security.addProvider(new BouncyCastleProvider());
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * AES加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encryptData(String data,String key) throws Exception {
        // 创建密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        //输出Base64编码后的结果
        return new String(Base64.getEncoder().encode(cipher.doFinal(data.getBytes())));
    }

    /**
     * AES解密
     *
     * @param base64Data
     * @return
     * @throws Exception
     */
    public static String decryptData(String base64Data,String key) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        //输出Base64编码解密后的结果
        return new String(cipher.doFinal(Base64.getDecoder().decode(base64Data)));
    }

    public static void main(String[] args) throws Exception {

        String key = "a43b7329cac6b4c740a977d554cabe";

        String phone = "134181008";
        //加密
        String phoneEncryptData = AES256ECB.encryptData(phone, key);
        //解密
        String temp = AES256ECB.decryptData(phoneEncryptData, key);
        System.out.println(String.format("加密前:%s \n加密后:%s \n解密后:%s", phone, phoneEncryptData, temp));

    }

}




